package com.bigfans.catalogservice.service.sku;


import com.bigfans.catalogservice.dao.SkuDAO;
import com.bigfans.catalogservice.model.SKU;
import com.bigfans.framework.cache.Cacheable;
import com.bigfans.framework.dao.BaseServiceImpl;
import com.bigfans.framework.utils.StringHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * @author lichong 2015年5月30日下午10:53:15
 * @Description:
 */
@Service(SkuServiceImpl.BEAN_NAME)
public class SkuServiceImpl extends BaseServiceImpl<SKU> implements SkuService {

    public static final String BEAN_NAME = "skuService";

    private SkuDAO skudao;

    @Autowired
    private StockLogService stockLogService;

    @Autowired
    public SkuServiceImpl(SkuDAO skuDAO) {
        super(skuDAO);
        this.skudao = skuDAO;
    }

    @Override
    @Transactional
    public void create(SKU e) throws Exception {
        if (StringHelper.isNotEmpty(e.getOptKey()) && StringHelper.isNotEmpty(e.getValKey())) {
            String optionKey = e.getOptKey();
            String valueKey = e.getValKey();
            String[] optKeys = optionKey.split(SKU.KEYS_SEPARATOR);
            String[] valKeys = valueKey.split(SKU.KEYS_SEPARATOR);
            if (optKeys.length != valKeys.length) {
                throw new Exception("sku option和value值个数不匹配");
            }
            StringBuilder skuKey = new StringBuilder();
            for (int i = 0; i < optKeys.length; i++) {
                skuKey.append(optKeys[i]);
                skuKey.append(SKU.SKU_SEPARATOR);
                skuKey.append(valKeys[i]);
                if (i < optKeys.length - 1) {
                    skuKey.append(SKU.KEYS_SEPARATOR);
                }
            }
            e.setSkuKey(skuKey.toString());
        }
        super.create(e);
    }

    @Override
    @Transactional(readOnly = true)
    public SKU getByPid(String pid) throws Exception {
        return skudao.getByPid(pid);
    }

    @Override
    @Transactional(readOnly = true)
    public List<SKU> listByPgId(String pgId) throws Exception {
        return skudao.listByPgId(pgId);
    }

    @Override
    @Transactional(readOnly = true)
    public List<SKU> listByProdId(String prodId) throws Exception {
        return skudao.listByProdId(prodId);
    }

    @Override
    @Transactional(readOnly = true)
    public SKU getByValKey(String valKey) throws Exception {
        return skudao.getByValKey(valKey);
    }
}
